import { Effect } from 'umi';
import { message } from 'antd';
import { fetchAllAppNotPage } from '@/services/app';
import { addCqBaseInfo, fetchAllCq, fetchCqDetail } from '@/services/cq';
import { querySysDict } from '@/services/system';
import { fetchUsersByRole } from '@/services/user';
import { AppItem } from '@/types/app';
import { CqItem } from '@/types/cq';
import { TradeResult } from '@/types/global';
import { BaseModelType } from './common';

export interface CqModelState {
  rows?: CqItem[];
  total?: number;
  pageSize?: number;
  appList?: AppItem[];
}

export interface CqModelType extends BaseModelType {
  namespace: 'cqs';
  state: CqModelState;
  effects: {
    fetchCqAddInitParams: Effect;
    addCqBaseInfo: Effect;
    fetchCqListInitParams: Effect;
    fetchAllCq: Effect;
    fetchCqDetail: Effect;
    updateCqState: Effect;
    unMount: Effect;
  };
}

const CqModel: CqModelType = {
  namespace: 'cqs',

  state: {
    rows: [],
    total: 0,
    pageSize: 10,
    appList: [],
  },

  effects: {
    *fetchCqAddInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ systemResponse, clusterResponse, auditorResponse, appListResponse ] = yield all([
          call(querySysDict, {
            dictName: 'system'
          }),
          call(querySysDict, {
            dictName: 'cluster'
          }),
          call(fetchUsersByRole, {
            roleCode: 'auditor'
          }),
          call(fetchAllAppNotPage, {})
        ]);
        // console.info(systemResponse);
        // console.info(auditorResponse);
        const systemSuccess =  systemResponse.success;
        const clusterSuccess =  clusterResponse.success;
        const auditorSuccess =  auditorResponse.success;
        const appListSuccess =  appListResponse.success;
        if (systemSuccess && clusterSuccess && auditorSuccess && appListSuccess) {
          const result1  = {
            systemData: [...systemResponse.result],
            clusterData: [...clusterResponse.result],
          };
          yield put({ type: 'systems/updateState', payload: result1 });
          const result2  = {
            ...auditorResponse.result
          };
          yield put({ type: 'users/updateState', payload: result2 });
          const result3 = {
            appList: [...appListResponse.result!.appList],
          };
          yield put({ type: 'updateState', payload: result3 });
        }
      } catch(e) {
        console.error(e);
        message.error('交易初始化失败');
      }
    },
    *addCqBaseInfo({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(addCqBaseInfo, payload);
        const { success } = response;
        if (success) {
          message.success('新增成功，请提醒主开人员处理');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('新增失败'); // 打印错误信息
        return false;
      }
    },
    *fetchCqListInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ systemResponse, auditorResponse, cqStatusResponse ] = yield all([
          call(querySysDict, {
            dictName: 'system'
          }),
          call(fetchUsersByRole, {
            roleCode: 'auditor'
          }),
          call(querySysDict, {
            dictName: 'cqStatus'
          }),
        ]);
        console.info(systemResponse);
        console.info(auditorResponse);
        console.info(cqStatusResponse);
        const systemSuccess =  systemResponse.success;
        const auditorSuccess =  auditorResponse.success;
        const cqStatusSuccess =  cqStatusResponse.success;
        if (systemSuccess && auditorSuccess && cqStatusSuccess) {
          const result1  = {
            systemData: [...systemResponse.result],
            cqStatusData: [...cqStatusResponse.result],
          };
          yield put({ type: 'systems/updateState', payload: result1 });
          const result2  = {
            ...auditorResponse.result
          };
          yield put({ type: 'users/updateState', payload: result2 });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fetchAllCq({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try{
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(fetchAllCq, payload);
        const { success } = response;
        if (success) {
          // 通讯成功取出数据
          const { result } = response;
          // 更新表格数据
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
      }
    },
    *fetchCqDetail({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        // 只有状态为 3-等待分配交易 才需要查询下挂的交易列表
        const response: TradeResult = yield call(fetchCqDetail, payload);
        const { success } = response;
        if (success) {
          const { result } = response;
          // 服务器端返回两个数据类型
          // 一个详细信息，一个交易列表
          // let { cqDetail, tradeList } = result;
          // if (!tradeList) {
          //   tradeList = []
          // }
          // const allResult = {
          //   result: {
          //     ...cqDetail,
          //     tradeList,
          //   }
          // }
          // console.info(allResult);
          return result;
        }
        return false;
      } catch(e) {
        console.error(e);
        message.error('数据获取失败'); // 打印错误信息
        return false;
      }
    },
    *updateCqState({ payload }, sagaEffects) {
      console.info('updateCqState', payload);
      const { put } = sagaEffects;
      yield put({ type: 'updateState', payload });
    },
    *unMount({ payload }, sagaEffects) {
      // console.info('updateCqState', payload);
      const { put } = sagaEffects;
      const result = {
        rows: [],
        total: 0,
        pageSize: 10,
      }
      yield put({ type: 'updateState', payload: result });
    }
  },

  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default CqModel;